import axios from 'axios'
import router from "@/router"
import sha256 from 'sha256'
import uuid from 'uuid/v1'
import moment from 'moment'

const http = axios.create({
  baseURL: config.baseUrl,
  timeout: 20 * 1000,
  withCredentials: true
})

// 请求拦截
http.interceptors.request.use(
  function (config) {
    // 组装报文：加签
    let client = 'web'
    let reqId = uuid()
    let token = localStorage.getItem('token')
    let userId = localStorage.getItem('userId')
    let loginName = localStorage.getItem('loginName')
    let time = moment().format('YYYY-MM-DD HH:mm:ss')
    let signature = ''
    if (token) {
      signature = sha256(time + reqId + token)
    }

    config.headers.client = client
    config.headers['req-id'] = reqId
    config.headers['req-time'] = time
    if (token) {
      config.headers['x-token'] = token
    }
    if (userId) {
      config.headers['user-id'] = userId
    }
    if (loginName) {
      config.headers['login-name'] = loginName
    }
    if (signature) {
      config.headers.signature = signature
    }
    return config
  },
  function (error) {
    console.log(error)
    return Promise.reject(error);
  })

//响应拦截
http.interceptors.response.use(
  function (response) {
    let pkgOut = response.data
    let code = pkgOut.code
    let errorMsg = pkgOut.message
    if (code !== 0) {
      console.log(errorMsg)
      return Promise.reject(errorMsg)
    }
    return response
  },
  function (error) {
    console.log(JSON.stringify(error))
    let msg = ''
    if (error.response) {
      if (error.response.status == 404) {
        msg = '无效的请求，请联系管理员！[' + error + ']'
      } else if (error.response.status == 401) {
        localStorage.removeItem('userId')
        localStorage.removeItem('token')
        localStorage.removeItem('loginName')
        msg = '登录信息验证失败，请重新登录！[' + error + "]"
        router.push('/')
      } else {
        msg = '系统错误，请联系管理员！[' + error + ']'
      }
    } else {
      msg = '通信失败！[' + error + ']'
    }
    // 返回接口返回的错误信息
    return Promise.reject(msg)
  }
)

export default http
